<?php

class RunTimeWorkflowNode extends AbstractRunTimeWorkflowNode
{
  /**
   * @var array $actions
   */
  protected $actions = null;

  protected function doDeliver ()
  {
    $this->object = new wfWorkflowWorkItem();
    $this->save();
    
    $this->workflow->handleWorkItemDelivered($this->design_time_node->getIdentifier());
  }

  /**
   * @param string $action
   * @return bool
   */
  public function canBeExecuted ($action = null)
  {
    if (! $this->design_time_node->hasAction($action))
    {
      throw new Exception();
    }
    return true;
  }

  /**
   * @param string $action
   */
  protected function doExecute ($action = null)
  {
    if (! is_null($this->actions))
    {
      $node_action = $this->actions[$action];
    }
    else
    {
      $node_action = $this->design_time_node->getAction($action)
        ->createRunTimeNodeAction($this);
    }
    $node_action->execute($this->getContainer());
  }

  protected function doComplete ()
  {
    $this->object->setCompletedAt(date('Y-m-d H:i:s'));
    $this->save();
    
    $this->workflow->handleWorkItemCompleted($this);
    $this->deliverFirstOutNode();
  }

  /**
   * @return WorkflowDesignTimeNode
   */
  public static function createDesignTimeNode ($identifier)
  {
    // TODO implement!!!
    $class = get_called_class();
    
    return new DesignTimeWorkflowNode($identifier, $class);
  }

  public function getActions ()
  {
    if (is_null($this->actions))
    {
      $design_time_actions = $this->design_time_node->getActions();
      $this->actions = array();
      foreach ($design_time_actions as $action)
      {
        $this->actions[$action->getIdentifier()] = $action->createRunTimeNodeAction($this);
      }
    }
    return $this->actions;
  }

  public function hasAction ($identifier)
  {
    return $this->design_time_node->hasAction($identifier);
  }
  
  public function hasActions() {
    return $this->design_time_node->hasActions();
  }
}